import * as dotenv from 'dotenv';
import * as path from 'path';

export class Config {
    private static config: { [key: string]: string | undefined } = {};

    public static async initialize(): Promise<void> {
        // 加载环境变量
        const envPath = path.resolve(process.cwd(), '.env');
        const result = dotenv.config({ path: envPath });

        if (result.error) {
            throw new Error(`Failed to load environment variables: ${result.error.message}`);
        }

        // 复制环境变量
        this.config = { ...process.env };

        // 验证必需的配置
        this.validateRequiredConfig();
    }

    private static validateRequiredConfig(): void {
        const requiredKeys = [
            'SERVER_PORT',
            'NODE_ENV',
            'MONGODB_URI',
            'REDIS_HOST',
            'REDIS_PORT',
            'JWT_SECRET'
        ];

        const missingKeys = requiredKeys.filter(key => !this.config[key]);
        if (missingKeys.length > 0) {
            throw new Error(`Missing required configuration: ${missingKeys.join(', ')}`);
        }
    }

    public static get(key: string): string {
        const value = this.config[key];
        if (value === undefined) {
            throw new Error(`Configuration key not found: ${key}`);
        }
        return value;
    }

    public static getNumber(key: string): number {
        const value = this.get(key);
        const num = Number(value);
        if (isNaN(num)) {
            throw new Error(`Configuration value is not a number: ${key} = ${value}`);
        }
        return num;
    }

    public static getBoolean(key: string): boolean {
        const value = this.get(key).toLowerCase();
        return value === 'true' || value === '1';
    }

    public static isDevelopment(): boolean {
        return this.get('NODE_ENV') === 'development';
    }

    public static isProduction(): boolean {
        return this.get('NODE_ENV') === 'production';
    }
} 